<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title></head>
<body>
<div> 发送消息</div>
<input type="text" id="msgContent"/> <input type="button" value=" 点击发送 " onclick="CHAT.chat()"/>
<div> 接收消息 :</div>
<div id="recMsg" style="background-color: gainsboro;"></div>
<script type="application/javascript">
    window.CHAT = {
        socket: null, init: function () {
            // 判断浏览器是否支持 websocket
            if (window.WebSocket) {
                // 支持 WebScoekt
                // 连接创建 socket ，注意要添加 ws 后缀
                CHAT.socket = new WebSocket("ws://127.0.0.1:9090/ws");
                CHAT.socket.onopen = function () {
                    console.log(" 连接建立成功 ");

                };
                CHAT.socket.onclose = function () {


                    console.log(" 连接关闭 ")
                };
                CHAT.socket.onerror = function () {
                    console.log(" 发生错误 ");
                };
                CHAT.socket.onmessage = function (e) {
                    console.log(" 接收到消息 :" + e.data);
                    var recMsg = document.getElementById("recMsg");
                    var html = recMsg.innerHTML;
                    recMsg.innerHTML = html + "<br/>" + e.data;
                };
            } else {
                alert(" 浏览器不支持 websocket 协议 "
                )
                ;
            }
        },
        chat: function () {
            var msg = document.getElementById("msgContent");
            CHAT.socket.send(msg.value);
        }
    }
    CHAT.init();
    </script>
</body>
</html>